<script setup lang="tsx">
import { defineExpose, inject, nextTick, ref } from 'vue';
import type { TreeProps } from 'ant-design-vue';
import { ElTree } from 'element-plus';
import { useAntdForm, useFormRules } from '@/hooks/common/form';
import { addRoyiRole, editRoyiRole, getRoyiMenuTreeSelect, getRoyiRoleById, roleMenuTreeselect } from '@/service/api';
import '/node_modules/element-plus/dist/index.css';

export type OperateType = AntDesign.TableOperateType;
interface Props {
  operateType: OperateType;
  rowData: any;
}

interface Model {
  roleName: any;
  roleKey: any;
  roleSort: any;
  status: any;
  remark: any;
  menuCheckStrictly: boolean;
}
const refreshList = inject('refreshList');

type RuleKey = Extract<keyof Model, 'roleName' | 'roleKey' | 'roleSort'>;
const props = defineProps<Props>();
const { createRequiredRule } = useFormRules();
const rules: Record<RuleKey, App.Global.FormRule> = {
  roleName: createRequiredRule('角色名称不能为空'),
  roleKey: createRequiredRule('权限字符不能为空'),
  roleSort: createRequiredRule('角色顺序不能为空')
};

const { formRef, validate, resetFields } = useAntdForm();
const model = ref<Model>(getMode());

function getMode(): Model {
  return {
    roleName: null,
    roleKey: null,
    roleSort: null,
    status: '0',
    remark: null,
    menuCheckStrictly: true
  };
}

const menuExpand = ref(false);
const menuNodeAll = ref(false);
const treeData = ref<TreeProps['treeData']>([]);
const menuRef = ref(null);
const defaultProps = {
  children: 'children',
  label: 'label'
};
async function getMenuTree() {
  const { data, error } = await getRoyiMenuTreeSelect();
  console.log('data :>> ', data);
  if (!error) {
    treeData.value = data;
  }
}
function handleCheckedTreeExpand(val) {
  for (let i = 0; i < treeData.value.length; i++) {
    menuRef.value.store.nodesMap[treeData.value[i].id].expanded = val.target.checked;
  }
}

function handleCheckedTreeNodeAll(val) {
  menuRef.value.setCheckedNodes(val.target.checked ? treeData.value : []);
}

function handleCheckedTreeConnect(val) {
  model.value.menuCheckStrictly = Boolean(val.target.checked);
  console.log('model.value.menuCheckStrictly :>> ', model.value.menuCheckStrictly);
}

function resetForm() {
  resetFields();
  menuRef.value.setCheckedNodes([]);
}

function getAllCheckedKeys() {
  const checkedKeys = menuRef.value.getCheckedKeys();
  const halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}

function submitForm() {
  const { roleName, roleKey, roleSort, status, remark } = model.value;
  const params: any = {
    roleName,
    roleKey,
    roleSort,
    status,
    menuIds: getAllCheckedKeys(),
    deptIds: [],
    menuCheckStrictly: true,
    deptCheckStrictly: true,
    remark
  };
  let pro;
  if (props.operateType == 'add') {
    pro = addRoyiRole(params);
  } else {
    params.roleId = currentRow.value.roleId;
    pro = editRoyiRole(params);
  }

  pro.then(({ data, error }) => {
    if (!error) {
      window.$message?.success('操作成功');
      refreshList(true, 1);
    } else {
      window.$message?.error('操作失败');
    }
  });
}

const currentRow = ref(null);
function getEditData(rowData) {
  currentRow.value = rowData;
  getRoyiRoleById(rowData.roleId).then(({ data, error }) => {
    const { roleName, roleKey, roleSort, status, remark, menuCheckStrictly } = data;
    model.value = { roleName, roleKey, roleSort, status, remark, menuCheckStrictly };
    roleMenuTreeselect(rowData.roleId).then( res => {
      const data = res.otherData;
      // 添加检查确保 data 和 checkedKeys 存在
      if (data && data.checkedKeys && Array.isArray(data.checkedKeys)) {
        const checkedKeys = data.checkedKeys;
        checkedKeys.forEach((v: any) => {
          nextTick(() => {
            menuRef.value && menuRef.value.setChecked(v, true, false);
          });
        });
      }
    });
  });
  // getRoyiRoleById(rowData.roleId).then(({ data, error }) => {
  //   const { roleName, roleKey, roleSort, status, remark, menuCheckStrictly } = data;
  //   model.value = { roleName, roleKey, roleSort, status, remark, menuCheckStrictly };
  //   roleMenuTreeselect(rowData.roleId).then(({ data, error }) => {
  //     console.log('data :>>11111 ', data);
  //     // 添加检查确保 data 和 checkedKeys 存在
  //     if (data && data.checkedKeys && Array.isArray(data.checkedKeys)) {
  //       const checkedKeys = data.checkedKeys;
  //       checkedKeys.forEach((v: any) => {
  //         nextTick(() => {
  //           menuRef.value && menuRef.value.setChecked(v, true, false);
  //         });
  //       });
  //     }
  //   });
  // });
}

defineExpose({
  getMenuTree,
  resetForm,
  submitForm,
  getEditData
});
</script>

<template>
  <AForm ref="formRef" :model="model" :rules="rules" :label-col="{ lg: 8, xs: 4 }" label-wrap>
    <ARow :gutter="20">
      <ACol :lg="12" :xs="24">
        <AFormItem name="roleName" label="角色名称" :label-col="{}">
          <AInput v-model:value="model.roleName" placeholder="请输入角色名称" autocomplete="off" />
        </AFormItem>
      </ACol>
      <ACol :lg="12" :xs="24">
        <AFormItem name="roleKey" :label-col="{}">
          <template #label>
            <ATooltip>
              <icon-ic-round-help class="align-sub text-icon" />
              <template #title>控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)</template>
            </ATooltip>
            权限字符
          </template>
          <AInput v-model:value="model.roleKey" placeholder="请输入角色名称" autocomplete="off" />
        </AFormItem>
      </ACol>
      <ACol :lg="12" :xs="24">
        <AFormItem name="roleSort" label="角色顺序" :label-col="{}">
          <AInputNumber v-model:value="model.roleSort" placeholder="请输入角色顺序" class="w-full" autocomplete="off" />
        </AFormItem>
      </ACol>
      <ACol :lg="12" :xs="24">
        <AFormItem name="status" label="状态" :label-col="{}">
          <ARadioGroup v-model:value="model.status">
            <ARadio value="0">正常</ARadio>
            <ARadio value="1">停用</ARadio>
          </ARadioGroup>
        </AFormItem>
      </ACol>
      <ACol :lg="12" :xs="24">
        <div class="lable w-full font-size-14px">菜单权限:</div>
        <ACheckbox v-model:checked="menuExpand" class="mt-5px" @change="handleCheckedTreeExpand($event)">
          展开/折叠
        </ACheckbox>
        <ACheckbox v-model:checked="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</ACheckbox>
        <div class="tree mt-8px max-h-200px w-full overflow-auto border-b-black">
          <ElTree
            ref="menuRef"
            class="menu-tree"
            :check-strictly="model.deptCheckStrictly"
            :data="treeData"
            show-checkbox
            node-key="id"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          />
        </div>
      </ACol>
      <ACol :lg="12" :xs="24"></ACol>
      <ACol :lg="24" :xs="24" class="mt-15px">
        <AFormItem name="remark" label="备注" :label-col="{}">
          <ATextarea v-model:value="model.remark" placeholder="请输入备注" :rows="4" autocomplete="off" />
        </AFormItem>
      </ACol>
    </ARow>
  </AForm>
</template>

<style lang="scss">
.menu-tree {
  .el-checkbox__input.is-checked .el-checkbox__inner,
  .el-checkbox__input.is-indeterminate .el-checkbox__inner {
    background-color: #646cff;
    border-color: #646cff;
  }

  .el-checkbox__inner {
    width: 16px;
    height: 16px;
    text-align: center;
  }
}
</style>
